﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.Domain.ViewModels.Authen.User;
using WaterRevenueMS.Core.Service.Authen;
using WaterRevenueMS.Componnent.Common;
using WaterRevenueMS.Componnent.Common.SecurityHelper;
using System.ComponentModel.Composition;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class LogonController : Controller
    {
        [Import]
        public IUserService UserService;
        
        public ActionResult Index()
        {
            //var entity=UserService.Users.FirstOrDefault();
            var model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult CheckLogon(LoginModel model)
        {
            OperationResult result = new OperationResult(OperationResultType.Warning, "用户名或密码错误");
            var user = UserService.Users.FirstOrDefault(t => t.LoginName == model.LoginName && t.IsDeleted == false);
            if(user!=null)
            {
                if (user.Enabled == false)
                {
                    result = new OperationResult(OperationResultType.Warning, "你的账户已经被禁用");
                }
                else if (DESProvider.DecryptString(user.LoginPwd) == model.LoginPwd)
                {
                    user.LastLoginTime = DateTime.Now;
                    user.LoginCount += 1;
                    UserService.Update(user);
                    result = new OperationResult(OperationResultType.Success, "登录成功");
                    Session["CurrentUser"] = user;
                    Session.Timeout = 20;
                }
            }
            return Json(result);
        }

        public ActionResult SignOut()
        {
            Session["CurrentUser"] = null;
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult ForgetPwd()
        {
            return PartialView();
        }

    }
}
